<template>
	<view class="container" :class="{ 'page-enter': isPageEnter, 'page-leave': isPageLeave }">
		<!-- 头部区域 -->
		<view class="header">
			<view class="header-top">
				<view class="back-btn" @click="handleBack">
					<text class="iconfont icon-back"></text>
					返回
				</view>
				<view class="header-title">{{testInfo.title}}</view>
				<view class="header-placeholder"></view> <!-- 用于平衡布局 -->
			</view>
			<view class="subtitle">请认真回答以下问题</view>
		</view>

		<!-- 选项：不再弹出测试 -->
		<view class="checkbox-container" v-if="showCheckbox">
		    <checkbox-group @change="handleCheckboxChange">
		        <label>
		            <checkbox value="1" :checked="nolongerPop === 1" /> 不再弹出测试
		        </label>
		    </checkbox-group>
		</view>

		<!-- 跳过按钮 -->
		<view class="skip-container" v-if="showSkip">
			<button class="skip-btn" @click="skipTest">跳过测试</button>
		</view>

		<!-- 顶部进度条 -->
		<view class="progress-bar">
			<view class="progress-text">第 {{currentIndex + 1}}/{{questions.length}} 题</view>
			<view class="progress-track">
				<view class="progress-fill" :style="{ width: `${(currentIndex + 1) / questions.length * 100}%` }"></view>
			</view>
		</view>

		<!-- 问题卡片 -->
		<view class="question-card">
			<view class="question-title">{{currentQuestion.question}}</view>
			<view class="options-list">
				<view 
					class="option-item" 
					v-for="(option, index) in currentQuestion.options" 
					:key="index"
					:class="{ 'selected': selectedOption === index }"
					@click="selectOption(index)"
				>
					<text class="option-text">{{option.label}}</text>
				</view>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="button-group">
			<button 
				class="nav-btn prev-btn" 
				:disabled="currentIndex === 0"
				@click="prevQuestion"
			>
				上一题
			</button>
			<button 
				class="nav-btn next-btn" 
				:disabled="!canNext"
				@click="nextQuestion"
			>
				{{currentIndex === questions.length - 1 ? '提交' : '下一题'}}
			</button>
		</view>
		<view class="dev-tools">
			<!-- 开发者快速跳转 -->
			<view class="dev-tool" v-if="isDev">
				<button class="dev-btn" @click="skipToLast">开发者：跳转到最后一题</button>
			</view>
			
			<!--开发者跳转，高风险结果-->
			<view class="dev-tool" v-if="isDev">
				<button class="dev-btn" @click="skipToLastW">开发者：跳转到最后一题且高风险</button>
			</view>
		</view>
	</view>
</template>

<script>
import { sclAnalyzeResults } from "./sclAnalyzeResults.js";
import { uclaAnalyzeResults } from "./uclaAnalyzeResult.js";
import { staiAnalyzeResults } from "./staiAnalyzeResults.js"
export default {
	data() {
		return {
			testId: "1",     //问卷id，默认为1
			questions: [], // 问题列表
			currentIndex: 0, // 当前问题索引
			selectedAnswer: '', // 当前选中的答案
			selectedOption: null, // 当前选中的选项索引
			canNext: false, // 是否可以进入下一题
			isLastQuestion: false, // 是否是最后一题
			isPageLeave: false, // 是否正在离开页面
			fromHome: false, // 是否从首页进入
			nolongerPop: 0, // 是否不再弹出测试
			hasCompleted: false, // 是否已完成测试
			lastSavedResult: null, // 最后一次保存的结果
			userAnswers: [], // 用户答案列表
			showSkip: true, // 是否显示跳过按钮
			showCheckbox: true, //是否显示勾选框
			isPageEnter: false,
			isSubmitting: false,// 添加提交状态锁
			testInfo: {
				title: '心理测试' // 默认标题
			}
		};
	},
	onLoad(options) {
		// 获取 fromHome 参数，决定是否显示跳过按钮
		if (options.fromHome === 'true') {
			this.showSkip = false;
			this.showCheckbox = false;
		} else {
			// 如果不是从首页进入，说明是首次登录自动进入，显示跳过按钮
			this.showSkip = true;
			this.showCheckbox = true;
		}
		//根据参数选择对应的问卷
		if(options.testId){
			this.testId = options.testId;
		}
		// 页面加载时触发进入动画
		setTimeout(() => {
			this.isPageEnter = true;
		}, 50);
	},
	onShow() {
		uni.hideHomeButton(); // 隐藏小房子图标
		// 隐藏右上角的 uniapp 图标
		uni.setNavigationBarColor({
			frontColor: '#ffffff',
			backgroundColor: '#ffffff'
		});
	},
	computed: {
		currentQuestion() {
			return this.questions[this.currentIndex] || null;
		},
		isLastQuestion() {
			return this.currentIndex === this.questions.length - 1;
		},
		isDev(){
			// return process.env.NODE_ENV === 'development';
			return false
		}
	},
	methods: {
		handleBack() {
		    uni.showModal({
		        title: '提示',
		        content: '确定要退出测试吗？您的答题进度将不会被保存',
		        confirmText: '退出',
		        cancelText: '取消',
		        success: (res) => {
		            if (res.confirm) {
		                this.isPageLeave = true;
		                setTimeout(() => {
		                    uni.navigateBack();
		                }, 300);
		            }
		        }
		    });
		},
		handleCheckboxChange(event) {
			this.nolongerPop = event.detail.value.length > 0 ? 1 : 0;
			console.log("checkbox 变更事件:", event.detail.value);
			console.log("nolongerPop 值:", this.nolongerPop);
		},
		async skipTest() {
			try {
				this.isPageLeave = true;
				await new Promise(resolve => setTimeout(resolve, 300));
				
				const res = await uniCloud.callFunction({
					name: 'updateTestFrequency',
					data: {
						action: 'skip',
						nolongerPop: this.nolongerPop,
						uniIdToken: uni.getStorageSync('uni_id_token')
					}
				});
				console.log('跳过测试:', res);
				uni.setStorageSync('hasSkippedTest', true);
				uni.switchTab({
					url:'/pages/index/index'
				});
			} catch (err) {
				console.error('跳过测试失败:', err);
				uni.showToast({ title: '操作失败', icon: 'none' });
			}
		},

		async fetchQuestions() {
			try {
				const res = await uniCloud.callFunction({
					name: 'getTestQuestions',
					data: { testId: this.testId }
				});
				if (res.result && res.result.code === 0) {
					this.questions = res.result.data;
					// 根据testId设置对应的测试名称
					switch(this.testId) {
						case "1":
							this.testInfo.title = "自我心理测试";
							break;
						case "2":
							this.testInfo.title = "孤独感测试";
							break;
						case "3":
							this.testInfo.title = "焦虑测试";
							break;
						default:
							this.testInfo.title = "心理测试";
					}
				} else {
					uni.showToast({ title: '获取题目失败', icon: 'none' });
				}
			} catch (error) {
				console.error('获取题目错误:', error);
				uni.showToast({ title: '网络错误', icon: 'none' });
			}
		},

		selectOption(index) {
			this.selectedOption = index;
			this.selectedAnswer = this.currentQuestion.options[index].value;
			this.canNext = true;
			
			// 更新当前问题的答案
			const currentAnswerIndex = this.userAnswers.findIndex(a => a.questionId === this.currentQuestion._id);
			if (currentAnswerIndex !== -1) {
				this.userAnswers[currentAnswerIndex] = {
					questionId: this.currentQuestion._id,
					answer: this.selectedAnswer
				};
			} else {
				this.userAnswers.push({
					questionId: this.currentQuestion._id,
					answer: this.selectedAnswer
				});
			}
		},

		nextQuestion() {
			if (!this.selectedAnswer) {
				uni.showToast({ title: '请选择一个选项', icon: 'none' });
				return;
			}
			console.log(this.questions)
			console.log(this.currentQuestion)
			// 更新当前问题的答案
			const currentAnswerIndex = this.userAnswers.findIndex(a => a.questionId === this.currentQuestion._id);
			if (currentAnswerIndex !== -1) {
				this.userAnswers[currentAnswerIndex] = {
					questionId: this.currentQuestion._id,
					answer: this.selectedAnswer
				};
			} else {
				this.userAnswers.push({
					questionId: this.currentQuestion._id,
					answer: this.selectedAnswer
				});
			}

			// 检查是否是最后一题
			if (this.currentIndex === this.questions.length - 1) {
				this.completeTest();
			} else {
				this.selectedAnswer = '';
				this.selectedOption = null;
				this.canNext = false;
				this.currentIndex++;
				
				// 如果下一题已有答案，则恢复答案
				const nextAnswer = this.userAnswers.find(a => a.questionId === this.questions[this.currentIndex]._id);
				if (nextAnswer) {
					this.selectedAnswer = nextAnswer.answer;
					this.selectedOption = this.questions[this.currentIndex].options.findIndex(opt => opt.value === nextAnswer.answer);
					this.canNext = true;
				}
			}
		},

	async completeTest() {
	  // 检查是否正在提交中
	  if (this.isSubmitting) {
		return;
	  }
	  
	  // 加锁
	  this.isSubmitting = true;
	  
	  try {
		if (!this.selectedAnswer) {
		  uni.showToast({ title: '请选择一个选项', icon: 'none' });
		  return;
		}
		
		// 更新当前问题的答案
		
		let result = {};
		// 分析结果
		if(this.testId == "1"){	
			result = sclAnalyzeResults(this.userAnswers);	
		}	
		else if(this.testId == "2"){	
			result = uclaAnalyzeResults(this.userAnswers);	
			console.log(result); 	
		}	
		else if(this.testId == "3"){	
			result = staiAnalyzeResults(this.userAnswers);	
		}
		
		// 保存题目+答案文本用于 AI 分析
		const aiContent = this.questions.map(q => {
		  const userAnswer = this.userAnswers.find(a => a.questionId === q._id);
		  const answerText = userAnswer
			? q.options.find(opt => opt.value === userAnswer.answer)?.label || '未知'
			: '未作答';
		  return [q.question, answerText];
		});

		
		uni.setStorageSync("aiContent", aiContent);
		
		console.log('正在进行testfrequency更新');
		
		// 更新 test_frequency 为 1
		try {
		  await uniCloud.callFunction({
			name: 'updateTestFrequency',
			data: {
			  action: 'complete',
			  nolongerPop: this.nolongerPop,
			  uniIdToken: uni.getStorageSync('uni_id_token')
			}
		  });
		} catch (err) {
		  console.error('更新测试状态失败:', err);
		}
		
		// 只有在未提交过时才保存结果
		if (!this.lastSavedResult) {
		  const res = await uniCloud.callFunction({
			name: 'saveMindTestResult',
			data: {
			  testId: this.testId,
			  result: result,
			  uniIdToken: uni.getStorageSync('uni_id_token')
			}
		  });
		  if (res.result.code === 0) {
			console.log('保存成功:', res.result.data.id);
			this.lastSavedResult = res.result.data.id;
		  } else {
			console.error('保存失败:', res);
		  }
		}
		
		// 显示成功提示并跳转
		this.isPageLeave = true;
		await new Promise(resolve => setTimeout(resolve, 300));
		
		uni.showToast({ title: '测试完成！', icon: 'success' });
		setTimeout(() => {
		  uni.redirectTo({
			url: `/testPages/result/result?result=${encodeURIComponent(JSON.stringify(result))}&testId=${this.testId}`
		  });
		}, 1500);
		
	  } finally {
		// 确保无论如何都会解锁
		setTimeout(()=>{
			this.isSubmitting = false;
		},1500)
		
	  }
	},

		prevQuestion() {
			if (this.currentIndex > 0) {
				this.currentIndex--;
				// 恢复当前问题的答案
				const currentAnswer = this.userAnswers.find(a => a.questionId === this.currentQuestion._id);
				if (currentAnswer) {
					this.selectedAnswer = currentAnswer.answer;
					this.selectedOption = this.currentQuestion.options.findIndex(opt => opt.value === currentAnswer.answer);
					this.canNext = true;
				} else {
					this.selectedAnswer = '';
					this.selectedOption = null;
					this.canNext = false;
				}
			}
		},

		skipToLast() {
			// 快速填充所有答案
			for (let i = 0; i < this.questions.length; i++) {
				this.userAnswers.push({
					questionId: this.questions[i]._id,
					answer: this.questions[i].options[0].value
				});
			}
			// 跳转到最后一题
			this.currentIndex = this.questions.length - 1;
			this.selectedAnswer = this.questions[this.currentIndex].options[0].value;
			this.selectedOption = 0;
			this.canNext = true;
		},
		//
		skipToLastW() {
			// 快速填充所有答案且最坏
			for (let i = 0; i < this.questions.length; i++) {
				this.userAnswers.push({
					questionId: this.questions[i]._id,
					answer: 4
				});
			}
			// 跳转到最后一题
			this.currentIndex = this.questions.length - 1;
			this.selectedAnswer = this.questions[this.currentIndex].options[0].value;
			this.selectedOption = 0;
			this.canNext = true;
		}
	},
	mounted() {
		this.fetchQuestions();
	}
};
</script>

<style lang="scss">
.container {
	padding: 30px;
	background: linear-gradient(135deg, #f0f4f7, #ffffff);
	min-height: 100vh;
	opacity: 0;
	transform: translateY(20rpx);
	transition: all 0.3s ease;
	
	&.page-enter {
		opacity: 1;
		transform: translateY(0);
	}
	
	&.page-leave {
		opacity: 0;
		transform: translateY(-20rpx);
	}
}
.header {
    text-align: center;
    margin-bottom: 40rpx;
    
    .header-top {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 16rpx;
    }
    
    .back-btn {
        font-size: 28rpx;
        color: #6c8eef;
        display: flex;
        align-items: center;
        
        .iconfont {
            margin-right: 8rpx;
        }
    }
    
    .header-title {
        font-size: 40rpx;
        font-weight: bold;
        color: #333;
        flex: 1;
        text-align: center;
    }
    
    .header-placeholder {
        width: 120rpx; /* 与返回按钮宽度一致保持平衡 */
    }
    
    .subtitle {
        font-size: 28rpx;
        color: #666;
    }
}
.checkbox-container {
	text-align: center;
	margin-bottom: 10px;
}
.progress-bar {
	padding: 30rpx;
	background: white;
	border-radius: 24rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 4rpx 12rpx rgba(108, 142, 239, 0.1);
}

.progress-text {
	font-size: 28rpx;
	color: #2c3e50;
	margin-bottom: 16rpx;
	text-align: center;
}

.progress-track {
	height: 8rpx;
	background: rgba(108, 142, 239, 0.1);
	border-radius: 4rpx;
	overflow: hidden;
}

.progress-fill {
	height: 100%;
	background: linear-gradient(135deg, #6c8eef 0%, #5a7de0 100%);
	border-radius: 4rpx;
	transition: width 0.3s ease;
}

.question-card {
	background: white;
	border-radius: 24rpx;
	padding: 40rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 4rpx 12rpx rgba(108, 142, 239, 0.1);
}

.question-title {
	font-size: 32rpx;
	color: #2c3e50;
	margin-bottom: 40rpx;
	line-height: 1.5;
	font-weight: 500;
}

.options-list {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.option-item {
	padding: 30rpx;
	background: rgba(108, 142, 239, 0.05);
	border-radius: 20rpx;
	transition: all 0.3s ease;
	border: 2rpx solid transparent;

	&.selected {
		background: rgba(108, 142, 239, 0.1);
		border-color: #6c8eef;
		transform: translateY(-2rpx);
		box-shadow: 0 4rpx 12rpx rgba(108, 142, 239, 0.1);
	}

	&:active {
		transform: translateY(-2rpx);
		box-shadow: 0 4rpx 12rpx rgba(108, 142, 239, 0.1);
	}
}

.option-text {
	font-size: 28rpx;
	color: #2c3e50;
	line-height: 1.4;
}

.button-group {
	display: flex;
	gap: 20rpx;
	padding: 30rpx 0;
}

.nav-btn {
	flex: 1;
	height: 88rpx;
	line-height: 88rpx;
	text-align: center;
	border-radius: 44rpx;
	font-size: 28rpx;
	font-weight: 500;
	border: none;
	transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
	position: relative;
	overflow: hidden;

	&::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: linear-gradient(135deg, #5a7de0 0%, #6c8eef 100%);
		opacity: 0;
		transition: opacity 0.3s ease;
	}

	&::after {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: linear-gradient(to right, transparent, rgba(255,255,255,0.3), transparent);
		transform: translateX(-100%);
		transition: transform 0.6s ease;
	}

	&:active {
		transform: translateY(-2rpx);
		box-shadow: 0 8rpx 16rpx rgba(108, 142, 239, 0.2);

		&::before {
			opacity: 1;
		}

		&::after {
			transform: translateX(100%);
		}
	}
}

.prev-btn {
	background: rgba(108, 142, 239, 0.1);
	color: #6c8eef;

	&:disabled {
		opacity: 0.5;
		background: rgba(108, 142, 239, 0.05);
	}
}

.next-btn {
	background: linear-gradient(135deg, #6c8eef 0%, #5a7de0 100%);
	color: white;

	&:disabled {
		opacity: 0.5;
		background: rgba(108, 142, 239, 0.5);
	}
}

.dev-tools {
	display: flex;
	flex-wrap: wrap;
	position: fixed;
	bottom: 40rpx;
	left: 50%;
	transform: translateX(-50%);
	z-index: 999;
}


.dev-btn {
	padding: 16rpx 32rpx;
	background: rgba(108, 142, 239, 0.1);
	color: #6c8eef;
	border-radius: 30rpx;
	font-size: 24rpx;
	border: 2rpx solid #6c8eef;
	transition: all 0.3s ease;

	&:active {
		background: rgba(108, 142, 239, 0.2);
		transform: translateY(-2rpx);
	}
}

.skip-container {
	text-align: right;
	margin-bottom: 20rpx;
}

.skip-btn {
	display: inline-block;
	padding: 12rpx 30rpx;
	background: rgba(108, 142, 239, 0.1);
	color: #6c8eef;
	border-radius: 30rpx;
	font-size: 26rpx;
	border: 2rpx solid #6c8eef;
	transition: all 0.3s ease;

	&:active {
		background: rgba(108, 142, 239, 0.2);
		transform: translateY(-2rpx);
	}
}
</style>
